package org.gaaidou.ptarmigan.springboot.functional.service.impl;

import org.gaaidou.ptarmigan.springboot.core.exception.Assert;
import org.gaaidou.ptarmigan.springboot.data.jpa.datasource.DataSourceRouteHelper;
import org.gaaidou.ptarmigan.springboot.data.jpa.datasource.DataSourceRouter;
import org.gaaidou.ptarmigan.springboot.functional.bean.RoutingDataSourceEntity;
import org.gaaidou.ptarmigan.springboot.functional.constant.DataSourceStrategy;
import org.gaaidou.ptarmigan.springboot.functional.dao.RoutingDataSourceDao;
import org.gaaidou.ptarmigan.springboot.functional.service.RoutingDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class RoutingDataSourceServiceImpl implements RoutingDataSourceService {

    @Autowired
    private RoutingDataSourceDao routingDataSourceDao;

    @DataSourceRouter(DataSourceStrategy.SECONDARY)
    @Override
    public String annoSecondary() {
        Optional<RoutingDataSourceEntity> routingDataSourceEntity = routingDataSourceDao.findById(1L);
        Assert.isTrue(routingDataSourceEntity.isPresent(), "");
        return routingDataSourceEntity.get().getName();
    }

    @DataSourceRouter(DataSourceStrategy.PRIMARY)
    @Override
    public String annoPrimary() {
        Optional<RoutingDataSourceEntity> routingDataSourceEntity = routingDataSourceDao.findById(1L);
        Assert.isTrue(routingDataSourceEntity.isPresent(), "");
        return routingDataSourceEntity.get().getName();
    }

    @Override
    public String helperSecondary() {
        return DataSourceRouteHelper.route(DataSourceStrategy.SECONDARY, () -> {
            Optional<RoutingDataSourceEntity> routingDataSourceEntity = routingDataSourceDao.findById(1L);
            Assert.isTrue(routingDataSourceEntity.isPresent(), "");
            return routingDataSourceEntity.get().getName();
        });
    }

    @Override
    public String helperPrimary() {
        return DataSourceRouteHelper.route(DataSourceStrategy.PRIMARY, () -> {
            Optional<RoutingDataSourceEntity> routingDataSourceEntity = routingDataSourceDao.findById(1L);
            Assert.isTrue(routingDataSourceEntity.isPresent(), "");
            return routingDataSourceEntity.get().getName();
        });
    }
}
